<template>
  <div>
    <div class="gva-table-box">
      <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          tooltip-effect="dark"
          row-key="ID"
          @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="需求发布日期" width="120">
          <template #default="scope">
            <span>{{ formatDate(scope.row.CreatedAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="订单ID" prop="ID" width="80" />
        <el-table-column align="left" label="订单Title" prop="title" />
        <el-table-column align="left" label="价格" width="150">
          <template #default="scope">
            <div>{{ scope.row.budgetMin }} ~ {{ scope.row.budgetMax }} 元</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="电话" prop="phone" />
        <el-table-column align="left" label="需求发布人" prop="nickname" />
        <el-table-column
            align="left"
            label="订单状态"
            prop="status"
            width="200"
        >
          <template #default="scope">
            <div>
              <el-tag :type="getTagType(scope.row.status)">
                {{ getTagLabel(scope.row.status) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="right" label="操作" min-width="160">
          <template #default="scope">
            <el-button
                type="primary"
                link
                icon="edit"
                @click="
                (event) => {
                  event.stopPropagation();
                  updateCustomer(scope.row);
                }
              "
            >编辑</el-button
            >
            <el-button
                type="primary"
                link
                icon="delete"
                @click="
                (event) => {
                  event.stopPropagation();
                  deleteCustomer(scope.row);
                }
              "
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-drawer
        v-model="drawerFormVisible"
        :before-close="closeDrawer"
        :show-close="false"
        size="30%"
        direction="rtl"
    >
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">订单处理选项</span>
          <el-button icon="close" @click="closeDrawer" circle></el-button>
        </div>
      </template>

      <el-form :inline="true" :model="form" label-width="120px">
        <!-- 单选按钮选择接单类型：外部接单、内部接单、返回需求 -->
        <el-form-item label="选择操作">
          <el-radio-group v-model="form.orderType">
            <el-radio label="external">外部接单</el-radio>
            <el-radio label="internal">内部接单</el-radio>
            <el-radio label="return">驳回需求</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 内部接单时显示额外的表单字段 -->
        <div v-if="form.orderType === 'internal'">
          <el-form-item label="技术方">
            <el-input
                v-model="form.technical"
                autocomplete="off"
                clearable
                placeholder="请输入技术方手机号"
                :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="价格">
            <el-input
              v-model="form.price"
              autocomplete="off"
              clearable
              placeholder="请输入价格,价格必须为整数"
              :style="{ width: '100%' }"
            />
          </el-form-item>
        </div>

        <!-- 返回需求时显示驳回理由 -->
        <div v-if="form.orderType === 'return'">
          <el-form-item label="驳回理由">
            <el-input
                v-model="form.rejectReason"
                type="textarea"
                rows="4"
                placeholder="请填写驳回理由"
                :style="{ width: '100%' }"
            />
          </el-form-item>
        </div>
      </el-form>

      <div class="flex justify-end mt-4">
        <el-button @click="closeDrawer" size="small">取 消</el-button>
        <el-button type="primary" @click="enterDrawer('submit')" size="small">
          提 交
        </el-button>
      </div>
    </el-drawer>
    <!-- 使用 el-dialog 作为模态框 -->
    <el-dialog
        v-model="dialogFormVisible"
        width="50%"
        :before-close="closeDialog"
    >
      <template #title>
        <div>订单详情</div>
      </template>

      <!-- 子组件 OrderDetail 传递 orderId -->
      <OrderDetail v-if="dialogFormVisible" :orderId="currentOrderId" />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { deleteCusOrder } from "@/api/customer/cusOrder";
import OrderDetail from "@/components/OrderDetails.vue";
import { ref,reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import { formatDate } from "@/utils/format";
import {
  backRequirement,
  editRequirement,
  getRequirementList,
} from "@/api/requirement";

defineOptions({
  name: "IDCheck",
});

const currentOrderId = ref(0);
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const dialogFormVisible = ref(false);
// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getTableData();
};

const handleCurrentChange = (val) => {
  page.value = val;
  getTableData();
};

// 查询
const getTableData = async () => {
  tableData.value = [];
  const table = await getRequirementList({
    page: page.value,
    pageSize: pageSize.value,
    type: 1,
  });
  if (table.code === 0) {
    tableData.value = table.data.list;
    total.value = table.data.total;
    page.value = table.data.page;
    pageSize.value = table.data.pageSize;
  }
};

getTableData();

// 处理点击行跳转
const handleRowClick = (row) => {
  currentOrderId.value = row.ID;
  dialogFormVisible.value = true; // 跳转到 OrderDetails 页面，并传递 id
};

const closeDialog = () => {
  dialogFormVisible.value = false;
};

const drawerFormVisible = ref(false);
const type = ref("");

const form = ref({
  orderType: "external", // 默认选择外部接单
  technical: "", // 技术方
  price: "", // 价格
  rejectReason: "", // 驳回理由
  row: {}, // 当前行数据，用于更新
});

const updateCustomer = (row) => {
  // const res = await findCusOrder({ id: row.ID });
  // type.value = "update";
  // if (res.code === 0) {
  //   form.value = res.data;
  //   drawerFormVisible.value = true;
  // }
  form.value.row = row;

  console.log(form.value);
  drawerFormVisible.value = true;
};
const closeDrawer = () => {
  drawerFormVisible.value = false;
  form.value = {
    orderType: "external", // 重置为默认外部接单
    technical: "",
    price: "",
    rejectReason: "", // 清空驳回理由
    row: {}, // 清空当前行数据
  };
};

const deleteCustomer = async (row) => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await deleteCusOrder({ ID: row.ID });
    if (res.code === 0) {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      if (tableData.value.length === 1 && page.value > 1) {
        page.value--;
      }
      getTableData();
    }
  });
};
// 提交时的逻辑
const enterDrawer = async (model) => {
  if (form.value.orderType === "return") {
    // 驳回请求前弹出确认框
    ElMessageBox.confirm("确定要驳回请求吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
        .then(async () => {
          // 用户确认后执行驳回请求
          const res = await backRequirement({
            order_id: form.value.row.ID,
            content: form.value.rejectReason,
            user_id: form.value.row.user_id,
          });
          if (res.code === 0) {
            ElMessage({
              type: "success",
              message: "驳回成功",
            });
          }
          getTableData();
          closeDrawer();
        })
        .catch(() => {
          // 用户取消驳回时的提示
          ElMessage({
            type: "info",
            message: "驳回已取消",
          });
        });
  } else if (form.value.orderType === "internal") {
    // 内部接单请求
	if(parseInt(form.value.price) > parseInt(form.value.row.budgetMax) || parseInt(form.value.price) < parseInt(form.value.row.budgetMin) ){
	   ElMessage({
		  type: "error",
		  message: "成交价格必须在区间内",
		});
		return 
	}
    if(form.value.technical == form.value.row.phone){
	   ElMessage({
		  type: "error",
		  message: "需求发布人和接单人不能是同一个人",
		});
		return 
	}
    const res = await editRequirement({
      type: 1,
      price: parseInt(form.value.price),
      phone: parseInt(form.value.technical),
      order_id: form.value.row.ID,
    });
    if (res.code === 0) {
      ElMessage({
        type: "success",
        message: "内部接单成功",
      });
    }
    console.log("内部接单内容：", form.value.technical, form.value.price);
    getTableData();
    closeDrawer();
  } else {
    // 外部接单请求
    const res = await editRequirement({
      type: 2,
      order_id: form.value.row.ID,
    });
    if (res.code === 0) {
      ElMessage({
        type: "success",
        message: "外部接单成功",
      });
    }
    getTableData();
    closeDrawer();
  }
};

const openDrawer = () => {
  // type.value = "create";
  drawerFormVisible.value = true;
};

// 根据 status 返回对应的 type
const getTagType = (status) => {
  switch (status) {
    case 0:
      return "warning";
    case 1:
      return "";
    case 3:
      return "danger";
    case 4:
      return "success";
    default:
      return "primary"; // 或者其他默认类型
  }
};
// 根据 status 返回对应的标签文本
const getTagLabel = (status) => {
  switch (status) {
    case 0:
      return "未提交";
    case 1:
      return "提交未审核";
    case 2:
      return "提交已认证失败";
    case 3:
      return "审核通过";
    default:
      return "未知";
  }
};
</script>

<style scoped>
.el-drawer__header {
  background-color: #f5f7fa; /* 标题栏背景色 */
  padding: 14px;
}

.el-drawer__body {
  padding: 20px;
}

.el-button {
  margin-left: 10px;
}

.flex {
  display: flex;
  justify-content: space-between;
}

.mt-4 {
  margin-top: 16px;
}
</style>
